<template>
   <div  class="app-container">
     <div class="visit"></div>
       <el-row :gutter="20" class="add-array">
           <el-col :span="2"> 
               <el-button
                     type="primary"
                     plain
                     icon="Plus"
                     @click="handleArray('添加参数组')"
                  >添加参数组</el-button>
               </el-col>
     </el-row>
      <el-row :gutter="20" style="margin-top:30px">
       <el-col :span="1.5">
        <el-tabs v-model="tabKey"
                  tab-position="left" 
                  class="tabs-top" 
                  @tab-click="handChanged"
                  @tab-change="handleClick">
           <el-tab-pane
                   v-for="item in editableTabs"
                   :key="item.id"
                   :label="item.name"
                   :name="item.id"
                   >
                   </el-tab-pane>
       </el-tabs>
       </el-col  >
         <el-col  :span="20">
            <el-row :gutter="10" class="mb8"
             style="line-height: 40px;
             text-align: center;" justify="space-between">
               <el-col :span="4.5">
                  <div><el-text>{{tabName}}配置</el-text> <el-button type="primary" plain icon="Plus" @click="handleAdd('添加参数项')" >添加参数项</el-button></div>
               </el-col>
               <el-col :span="5.5">
                 <el-button type="primary" plain icon="CopyDocument" @click="handleCopy">引用</el-button>
                  <el-button type="info" plain icon="Edit" @click="handleArray('编辑参数组')">编辑</el-button>
                  <el-button type="danger" plain icon="Delete" @click="delArray" >删除</el-button>
               </el-col>
            </el-row>
            <el-table v-loading="loading"  border :data="pamaterValueList">
               <el-table-column label="参数名" align="center" key="name" prop="name"  />
               <el-table-column label="参数类型" align="center" key="parameter" prop="parameter" >
                 <template #default="scope">
                    <div v-if="scope.row.parameter=='1'">输入框</div>
                    <div v-else>选择项{{scope.row.multiple=='2'?"（多选）":'（单选）'}}</div>
                 </template>
               </el-table-column>
               <el-table-column label="可选择值" align="center" key="options" prop="options"  >
                 <template #default="scope">
                    <div v-if="!scope.row.options">-</div>
                    <div v-else>{{scope.row.options}}</div>
                 </template>
               </el-table-column>
               <el-table-column label="必填" align="center" key="required" prop="required"  >
                 <template #default="scope">
                    <div v-if="scope.row.required=='1'">是</div>
                    <div v-else>否</div>
                 </template>
               </el-table-column>
               <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-tooltip content="编辑" placement="top" >
                        <el-button link type="primary" icon="Edit" @click="editItem(scope.row)" ></el-button>
                     </el-tooltip>
                     <el-tooltip content="删除" placement="top">
                        <el-button link type="primary" icon="Delete" @click="delItem(scope.row)"></el-button>
                     </el-tooltip>
                     <el-tooltip content="上移" placement="top" >
                        <el-button link type="primary" icon="ArrowUp" @click="upDownItem(scope.row,scope.$index ,true)"></el-button>
                     </el-tooltip>
                     <el-tooltip content="下移" placement="top" >
                        <el-button link type="primary" icon="ArrowDown" @click="upDownItem(scope.row,scope.$index ,false)"></el-button>
                     </el-tooltip>
                  </template>
               </el-table-column>
            </el-table>
         </el-col>
      </el-row>

      <!-- 新增与修改参数组对话框 -->
      <el-dialog :title="titleArrayName" v-model="addArrayShow" width="600px" append-to-body>
         <el-form :model="formArray" :rules="rules" ref="addArrayRef" label-width="100px">
            <el-row>
               <el-col :span="16">
                  <el-form-item prop="name" label="参数组名称">
                   <el-input v-model="formArray.name" placeholder="请输入参数组名称" maxlength="30" />
                  </el-form-item>
                  <el-form-item label="参数组分类" prop="parent_id">
                     <el-select
                        v-model="formArray.parent_id"
                        placeholder="请选择"
                        style="width: 293px"
                        @visible-change ='getClassifiedList'
                     >
                       <el-option
                       v-for="dict in arrayList"
                       :key="dict.id"
                       :label="dict.name"
                       :value="dict.id"
                       />
                     </el-select>
                  </el-form-item>
                  <el-form-item label="排序值"  prop="sortNum">
                     <el-input 
                     v-model="formArray.sortNum" 
                     placeholder="" 
                     maxlength="3"
                     oninput="if(value>100){value=100}else{value=value.replace(/[^\d]/g,'')}if(value.indexOf(0)==0){value=0}" />
                     <div class="tips">排序值越小显示越靠前,不填写默认为0</div> 
                  </el-form-item>
                  <el-form-item label="是否启用" prop="status">
                     <el-radio-group v-model="formArray.status">
                        <el-radio
                           v-for="dict in enableUse"
                           :key="dict.value"
                           :label="dict.value"
                        >{{ dict.label }}</el-radio>
                     </el-radio-group>
                     <div class="tips">启用后在配置担保产品时，可使用该参数组</div> 
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">提交</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
     
       <!-- 新增与编辑参数项对话框 -->
       <el-dialog :title="titleItemName" v-model="addItemShow" width="600px" append-to-body>
         <el-form :model="formItme" :rules="rulest"  ref="viewItemRef" label-width="100px">
            <el-row>
               <el-col :span="16">
                  <el-form-item  label="参数名" prop="name">
                     <el-input  
                         v-model="formItme.name"
                         placeholder="" 
                           onkeyup="value= value.replace(/\s+/g,'')"
                            maxlength="30" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="16">
                  <el-form-item label="参数类型" prop="parameter">
                     <el-select
                        v-model="formItme.parameter"
                        placeholder="请选择"
                        style="width: 293px"
                     >
                       <el-option
                       v-for="dict in typeArr"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"
                       />
                   </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="16" v-if="formItme.parameter==1">
                 <el-form-item label="正则校验" prop="verify">
                    <el-input  
                         v-model="formItme.verify"
                            placeholder="" 
                           onkeyup="value= value.replace(/\s+/g,'')"
                            maxlength="100" />
                 </el-form-item>
               </el-col>
               <el-col :span="16" v-if="formItme.parameter==2">
                  <el-form-item  label="" prop="multiple">
                   <el-radio-group v-model="formItme.multiple" class="ml-4" >
                              <el-radio label="1">单选项</el-radio>
                              <el-radio label="2">多选项</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row  v-if="formItme.parameter==2">
               <el-col :span="16" >
                  <el-form-item label="选项值"  prop="options">
                     <el-input 
                        v-model="formItme.options" 
                        placeholder="请输入可选择项，用回车分隔"
                         rows="5"
                         type="textarea" 
                         onkeyup="value= value.replace(/[ ]/g,'')"/>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="16">
                  <el-form-item label="是否必填" prop="required">
                   <el-switch
                                   v-model="formItme.required"
                                   inline-prompt
                                   active-text="必填"
                                   inactive-text="非必填"
                                   :active-value='activeValue'
                                   :inactive-value='inactiveValue'
                               />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="16">
                 <el-form-item label="是否启用" prop="status">
                     <el-radio-group v-model="formItme.status">
                        <el-radio
                           v-for="dict in enableUse"
                           :key="dict.value"
                           :label="dict.value"
                        >{{ dict.label }}</el-radio>
                     </el-radio-group>
                     <div class="tips">启用后在配置担保产品时，可使用该参数组</div> 
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer >
            <div class="dialog-footer">
               <el-button type="primary" @click="submitItemForm">提交</el-button>
               <el-button @click="addItemShow=false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Parameter">
import { parameterAdd ,
         parameterList , 
         parameterDel , 
         parameterUpdate,
         parameterUpdateSortNum,
         parameterCopy} from "@/api/product/parameter";
import { ElMessage, ElMessageBox } from 'element-plus'
const router = useRouter();
const { proxy } = getCurrentInstance();
const tabKey = ref('0');
const tabName = ref('');
const editableTabs = ref([])
const titleArrayName = ref('添加参数组');
const addArrayShow = ref(false);
const arrayList = ref([])
const titleItemName = ref('添加参数项');
const copyFlag = ref(false)
const addItemShow = ref(false);
const pamaterValueList = ref([]);
const loading = ref(false);
const activeValue = ref(1)
const inactiveValue = ref(0)
const enableUse = ref([{ value:1,label:'是'},{value:2,  label:'否'}]);
const typeArr  = ref([{ value:1,label:'输入项'},{ value:2, label:'选择项'}]);
const data = reactive({
   formArray:{},
   formItme:{},
  rules: {
     parent_id: [{ required: true, message: "请选择参数组分类", trigger: "change" }],
     name:[{ required: true, message: "参数组名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "参数组名称长度必须介于 2 和 20 之间", trigger: "blur" }],
  },
  rulest:{
   name:[{ required: true, message: "参数名不能为空", trigger: "blur" }, { min: 2, max: 20, message: "参数名长度必须介于 2 和 20 之间", trigger: "blur" }],
   parameter: [{ required: true, message: "请选择参数类型", trigger: "change" }],
   multiple: [{ required: true, message: "请选择类型", trigger: "change" }],
   options:[{ required: true, message: "输入项为空", trigger: "blur" }, { min: 1, max: 2000, message: "输入项长度必须介于 1 和 2000 之间", trigger: "blur" }],
  }
});

const { formArray,formItme, rules ,rulest} = toRefs(data);

/** 获取参数列表 */
 function getParamterList(type,vl){
  return parameterList({
     type:type,
     parent_id:vl,
     page_size:"-1",
     page_count:"-1"
  })
}
 /** 获取参数组列表 */
async function getParamterArray(){
   editableTabs.value =[]
    let result  = await getParamterList('2','') 
    if(result.data.list.length>0){
     editableTabs.value = result.data.list;
     tabName.value =  editableTabs.value[0].name;
     tabKey.value = editableTabs.value[0].id;
     let timer = setTimeout(()=>{
         clearTimeout(timer)
        getList(tabKey.value);
     },1100)
    }
}
/*切换参数组**/
function handleClick(vl){
  getList(tabKey.value);
}
function handChanged(vl){
   tabName.value =  vl.props.label;
}
/**引用*/
function handleCopy(){
      addArrayShow.value = true;
      resetForm()
      titleArrayName.value = '添加参数组';
      copyFlag.value = true;
}
/**参数分类获取*/
async function getClassifiedList(vl){
  if(vl){
     let result  = await getParamterList('1','') 
     if(result.data.list.length>0){
        arrayList.value = result.data.list;
       }
  }
}
/** 查询参数项列表 */
async function getList(id) {
      loading.value = true;
  let result  = await getParamterList('3',id) 
      loading.value = false;
    if( result.data.list.length > 0 ){
       pamaterValueList.value = result.data.list;
    }else{
       pamaterValueList.value = []
    }
};
/**重置参数组*/
function resetForm(){
  formArray.value ={
     type : '2',
     name : undefined,
     status : undefined,
     sortNum : undefined,
    parent_id : undefined
  }
  proxy.resetForm("addArrayRef");
}
 /** 新增与编辑参数组操作 */
async function handleArray(val) {
      addArrayShow.value = true;
      resetForm()
      titleArrayName.value = val;
      if(val=='编辑参数组'){
        let result  = await getParamterList('1','') 
     if(result.data.list.length>0){
        arrayList.value = result.data.list;
       }
        let arr = editableTabs.value.filter(item => { return item.id == tabKey.value;});
         formArray.value ={
                id : arr[0].id,
                type : '2',
                name : arr[0].name,
                status : arr[0].status,
               sortNum : arr[0].sort_num,
               parent_id : arr[0].parent_id
         }
      }
 }
 /** 删除参数组操作 */
function delArray(val) {
   ElMessageBox({
   title: '删除确认',
   message: h('p', null, [
     h('p', null, '确定要删除参数组吗？'),
     h('p', { style: 'color: red' }, '会同时删除其对应的参数项，不能删除已使用的删除组'),
   ]),
   showCancelButton: true,
   confirmButtonText: '确定',
   cancelButtonText: '取消',
   beforeClose: (action, instance, done) => {
     if (action === 'confirm') {
         parameterDel(tabKey.value).then(res=>{
           if(res.data){
              proxy.$modal.msgSuccess("删除成功");
           }else{
              proxy.$modal.msgWarning(res.msg);
           }
            done()
               getParamterArray();
         }) ;
     } else {
       done()
     }
   },
 }).then((action) => {
   
 })
 }
 /**重置参数项*/
 function resetFormItme(){
  formItme.value = {
     name:undefined,
     parameter:undefined,
     multiple:undefined,
     options:undefined,
     required:0,
     status:1
  }
  proxy.resetForm("viewItemRef");
}
 /** 新增参数项操作 */
function handleAdd(val) {
   addItemShow.value = true;
   resetFormItme();
   titleItemName.value = val;
}
/**编辑参数项*/
function editItem(row){
  console.log(row,'编辑参数项')
   addItemShow.value = true;
   resetFormItme();
   titleItemName.value ='编辑参数项';
   formItme.value = {
        id:row.id,
        name:row.name,
        parameter:row.parameter,
        multiple:row.multiple?.toString(),
        options:row.options?row.options.replaceAll(',', '\n'):row.options, 
        required:row.required ,
        verify:row.verify,
        status:row.status
   }
}

 /**参数项提交*/
 function submitItemForm(){
   proxy.$refs["viewItemRef"].validate(valid => {
       if(valid){
        if(titleItemName.value == '添加参数项'){
           parameterAdd({
               ...formItme.value,
               type:"3",
               parent_id:tabKey.value,
               options : formItme.value.options?.split('\n').toString()
           }).then(response => {
              if(response.code=='200'&& response.data){
                    proxy.$modal.msgSuccess("新增成功");
                     addItemShow.value = false;
                     getList(tabKey.value);
              }else{
                 proxy.$modal.msgWarning(response.msg);
              };
                   
             });
         }else{
           parameterUpdate({
               ...formItme.value,
               type:"3",
               parent_id:tabKey.value,
               options : formItme.value.options?.split('\n').toString()
           }).then(response => {
                 if(response.code=='200'&& response.data){
                       addItemShow.value = false;
                       getList(tabKey.value);
                       proxy.$modal.msgSuccess("修改成功");
                 }else{
                      proxy.$modal.msgWarning(response.msg);
                 }
                 
            })
         }
       }
   })
 }
 /**删除参数项提交*/
 function delItem(row){
  proxy.$modal.confirm('是否确认删除参数项？').then(function () {
        return parameterDel(row.id) ;
     }).then((res) => {
        if(res.code='200' && res.data){
           getParamterArray();
        proxy.$modal.msgSuccess("删除成功");
        }else{
           proxy.$modal.msgWarning(res.msg);
        }
     }).catch(() => {});
 }
/**上下移参数项提交*/
function upDownItem(row,index,vl){
   if(vl){
     if(index!='0'){
        parameterUpdateSortNum({
           up_id:pamaterValueList.value[index].id,
           up_sort_num:pamaterValueList.value[index].sort_num,
           down_id:pamaterValueList.value[index-1].id,
           down_sort_num:pamaterValueList.value[index-1].sort_num,
        }).then(res=>{
           getList(tabKey.value);
        })
     }else{
        proxy.$modal.msgWarning("该参数项不能上移");
     }
   }else{
     if(index!=pamaterValueList.value.length-1){
        parameterUpdateSortNum({
           up_id:pamaterValueList.value[index+1].id,
           up_sort_num:pamaterValueList.value[index+1].sort_num,
           down_id:pamaterValueList.value[index].id,
           down_sort_num:pamaterValueList.value[index].sort_num,
        }).then(res=>{
           getList(tabKey.value);
        })
     }else{
        proxy.$modal.msgWarning("该参数项不能下移");
     }
   }
}

/** 取消按钮 */
function cancel() {
  addArrayShow.value = false;
  proxy.resetForm("addArrayRef");
};
/** 提交参数组按钮 */
function submitForm() {
  proxy.$refs["addArrayRef"].validate(valid => {
    if (valid) {
         if(titleArrayName.value == '添加参数组'){
           if(copyFlag.value){
              parameterCopy({
               ...formArray.value,
               type:"2",
               sortNum:formArray.value.sortNum==''?0:formArray.value.sortNum
           },tabKey.value).then(response => {
                     if(response.code=='200'&& response.data){
                        proxy.$modal.msgSuccess("引用成功");
                       addArrayShow.value = false;
                       getParamterArray();
                     }else{
                        proxy.$modal.msgWarning(response.msg);
                     }
                    
             });
           }else{
              parameterAdd({
               ...formArray.value,
               type:"2",
               sortNum:formArray.value.sortNum==''?0:formArray.value.sortNum
           }).then(response => {
                  if(response.code=='200'&& response.data){
                     proxy.$modal.msgSuccess("新增成功");
                           addArrayShow.value = false;
                           getParamterArray();
                  }else{
                     proxy.$modal.msgWarning(response.msg);
                  }     
             });
           }
         }else{
           parameterUpdate({
               ...formArray.value,
               sortNum:formArray.value.sortNum==''?0:formArray.value.sortNum
           }).then(response => {
            if(response.code=='200'&& response.data){
                  proxy.$modal.msgSuccess("更新成功");
                  addArrayShow.value = false;
                  getParamterArray();
            }else{
               proxy.$modal.msgWarning(response.msg);
            }
            })
         }
    }
  });
};
getParamterArray();
</script>
<style scoped>
.app-container{
   padding-top: 0;
}
.add-array{
   line-height: 62px;
   border-bottom:1px solid black ;
}
.explain{
   line-height: 40px;
   font-size: 12px;
   margin-left:90px;
}
</style>
